package com.dk.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /*
    * 创建ShiroFilterFactoryBean
    * */
    @Bean
    public ShiroFilterFactoryBean filterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        /*
        * 常用的过滤器
        * anon : 无需登录认证 可以访问
        *  authc:必须认证才可以访问
        *   user:如果使用rememberMe的功能才能访问
        *   perms:该资源必须得到资源权限才可以访问
        *   role:该资源必须得到角色权限才可以访问
        * */
        Map<String,String> fileMap = new LinkedHashMap<>();
        fileMap.put("/index","anon");
        fileMap.put("/crud/select","anon");

        fileMap.put("/login", "anon");
        fileMap.put("/crud/delete","perms[delete_perm]");//permissions 权限
        fileMap.put("/crud/insert","perms[insert_perm]");//permissions 权限

        //退出
        fileMap.put("/logout","logout");
        //拦截所有
        fileMap.put("/**","authc");
        //调整登录页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //没有权限跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorizedUrl");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(fileMap);
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager());
        return shiroFilterFactoryBean;
    }
    /*
    * 创建DefaultWebSecurityManager 安全管理器
    * */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(getRealm());
        return securityManager;
    }
    //创建realm
    @Bean
    public UserRealm getRealm(){
        UserRealm userRealm = new UserRealm();
      //设置加密方式
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return  userRealm;
    }
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
       //加密方式
        matcher.setHashAlgorithmName("MD5");
        //设置加密编码格式
        matcher.setStoredCredentialsHexEncoded(true);
        //设置加密次数
        matcher.setHashIterations(5);
        return matcher;
    }

}
